//
//  SEGActivityCommentDetailViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/8.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "SEGActivityCommentDetailViewController.h"
#import "SEGActivityDetailCommentCell.h"
#import "SEGActivityDetailToolBarView.h"
#import "SEGCommentInputView.h"
#import "SEGCommunitySocialManager.h"
#import "SEGActivityCommentDetailViewModel.h"


@interface SEGActivityCommentDetailViewController () <UITableViewDelegate, UITableViewDataSource, SEGActivityDetailToolBarDelegate, SEGActivityDetailCommentCellDelegate, SEGCommentInputViewDelegate, SEGTextViewDelegate>


/**
 主视图
 */
@property (nonatomic, strong)UITableView *tableView;


@property (nonatomic, strong) SEGInputBarView* inputBarView;
/**
 输入界面及背景视图
 */
@property (nonatomic, strong) SEGCommentInputView *commentInputView;

@property (nonatomic, strong) SEGActivityCommentDetailViewModel *viewModel;


@end

@implementation SEGActivityCommentDetailViewController
- (instancetype)initWithQuizId:(NSString *)quizId actId:(NSString *)actId actName:(NSString *)actName {
    if (self = [super init]) {
        self.viewModel = [[SEGActivityCommentDetailViewModel alloc] initWithQuizId:quizId actId:actId actName:actName];
    }
    return self;
}
//头部刷新逻辑
- (void)headerRereshing
{
    [self loadDataWithRefresh:YES];
}

//底部刷新逻辑
- (void)footerRereshing
{
    [self loadDataWithRefresh:NO];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kColor_W;
    [self showCustomNavigationBackButton];
    self.title = @"邻居说";
    [self.view addSubview:self.tableView];
    
    WeakSelf;
    [self.tableView addWindmillWithHeaderRefreshBlock:^{
        [weakSelf headerRereshing];
    } footerRefreshBlock:^{
        [weakSelf footerRereshing];
    }];
    [self.tableView beginHeaderRefreshing];
    
    self.inputBarView = [[SEGInputBarView alloc] init];
    self.inputBarView.textView.delegate = self;
    [self.view addSubview:self.inputBarView];
    [self.inputBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.height.mas_equalTo(KSEGInputBarViewHeight+LYSafeAreaBottom());
    }];
    self.inputBarView.placeholderText = KInputToolBarDefalutDesc;
    [self.inputBarView.sendButton addTarget:self action:@selector(sendButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    //    [self seg_loadNeedShowAd];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.commentInputView.hidden = NO;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    self.commentInputView.hidden = YES;
}

- (void)dealloc
{
    [self.commentInputView removeFromSuperview];
    self.commentInputView = nil;
}

#pragma mark - 数据请求
- (void)loadDataWithRefresh:(BOOL)refresh {
    [self loadQuizDetailByQuizId];
    [self loadQuizAnswListByQuizIdWithRefresh:refresh];
}
//顶部展示数据请求
- (void)loadQuizDetailByQuizId
{
    [[self.viewModel.activityCommentDetailCommand execute:@""] subscribeNext:^(id  _Nullable x) {
        [self.tableView stopAnimatingWindmill];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    } completed:^{
        [self.tableView reloadData];
    }];
}

//底部评论数据请求
- (void)loadQuizAnswListByQuizIdWithRefresh:(BOOL)refresh
{
    [[self.viewModel.quizAnswListCommand execute:[[NSNumber alloc] initWithBool:refresh]]  subscribeNext:^(id  _Nullable x) {
        [self.tableView stopAnimatingWindmill];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        if ([error.localizedDescription isEqualToString:@"没有更多的数据！"]) {
            NSInteger lastRow = self.viewModel.activityManager.commentAnswerList.count - 1;
            if (lastRow >= 0) {
                /*
                 注：这个页面在数据只有三四条评论的时候，上拉加载的动效收不起来，未找到原因，暂时做强行滚动的处理
                 */
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:lastRow inSection:1] atScrollPosition:UITableViewScrollPositionNone animated:YES];
            }
        }
    } completed:^{
        [self.tableView reloadData];
    }];
}


#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0://评论主贴
        {
            return 1;
        }
        default://评论的回复
        {
            return self.viewModel.activityManager.commentAnswerList.count;
        }
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = indexPath.section;
    switch (section) {
        case 0://评论主贴
        {
            SEGActivityDetailCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kActivityDetailCommentCellIdentifier forIndexPath:indexPath];
            cell.delegate = self;
            [cell setUpCellWithCommentDetailModel:self.viewModel.activityManager.commentDetailModel indexPath:indexPath];
            return cell;
        }
        default://评论的回复
        {
            SEGActivityDetailCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kActivityDetailCommentCellIdentifier forIndexPath:indexPath];
            cell.delegate = self;
            [cell setUpCellWithCommentAnswerModel:self.viewModel.activityManager.commentAnswerList[indexPath.row] indexPath:indexPath];
            return cell;
        }
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSString *key = [NSString stringWithFormat:@"%@ %ld %ld",self.viewModel.activityManager.commentDetailModel.quizId, (long)indexPath.section, (long)indexPath.row];
        [self.viewModel.cellHightDict setObject:@(cell.frame.size.height) forKey:key];
    } else {
        if (self.viewModel.activityManager.commentAnswerList.count > indexPath.row) {
            SEGActivityDetailCommentAnswModel *model = self.viewModel.activityManager.commentAnswerList[indexPath.row];
            NSString *key = [NSString stringWithFormat:@"%@ %ld %ld",model.answId, (long)indexPath.section, (long)indexPath.row];
            [self.viewModel.cellHightDict setObject:@(cell.frame.size.height) forKey:key];
        }
    }
}

- (CGFloat)tableView:(UITableView*)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    CGFloat height = 0;
    if (indexPath.section == 0) {
        NSString *key = [NSString stringWithFormat:@"%@ %ld %ld",self.viewModel.activityManager.commentDetailModel.quizId, (long)indexPath.section, (long)indexPath.row];
        height = [[self.viewModel.cellHightDict objectForKey:key] doubleValue];
    } else {
        if (self.viewModel.activityManager.commentAnswerList.count > indexPath.row) {
            SEGActivityDetailCommentAnswModel *model = self.viewModel.activityManager.commentAnswerList[indexPath.row];
            NSString *key = [NSString stringWithFormat:@"%@ %ld %ld",model.answId, (long)indexPath.section, (long)indexPath.row];
            height = [[self.viewModel.cellHightDict objectForKey:key] doubleValue];
        }
    }
    return height ?: 88.0;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.01;
    } else {
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 10.0)];
    header.backgroundColor = kColor_bg;
    return header;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section != 0) {
        [self seg_comementCellAtIndexPath:indexPath];
    }
}

#pragma mark - SEGActivityDetailCommentCellDelegate
//评论
- (void)cellCommentButtonActionWithIndexPath:(NSIndexPath *)indexPath
{
    [self seg_comementCellAtIndexPath:indexPath];
}

//点赞
- (void)cellPraiseButtonActionWithIndexPath:(NSIndexPath *)indexPath
{
    [[self.viewModel.praiseCommand execute:indexPath] subscribeCompleted:^{
        [self.tableView reloadData];
    }];
}

- (void)cellImageTapWithImageUrlArray:(NSArray *)arr SelectedImageView:(UIImageView*)image SelectedIndex:(NSInteger)index
{
    [SEGPhotoBrower segBrowPhotoWithDataArray:arr
                            SelectedImageView:image
                                SelectedIndex:index
                                     FromView:self.navigationController.view];
    
}

#pragma mark - SEGActivityDetailToolBarDelegate
- (void)sendButtonActionWithContent:(NSString *)content
{
    [self.view endEditing:YES];
    
    [[self.viewModel.saveQuizAnswerCommand execute:content] subscribeNext:^(NSNumber *x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        }else {
            [SVProgressHUD dismiss];
        }
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        if (error.code == 1001) {
            [self.commentInputView hiddenCommentInputView];
            [self.commentInputView setPlaceholderText:KInputToolBarDefalutDesc];
            //重新所有数据请求
            [self headerRereshing];
        }
    } completed:^{
        [self.commentInputView hiddenCommentInputView];
        [self.commentInputView setPlaceholderText:KInputToolBarDefalutDesc];
        //重新所有数据请求
        [self headerRereshing];
    }];

}
#pragma mark - SEGTextViewDelegate
-(BOOL)textViewShouldBeginEditing:(SEGTextView *)textView
{
    // 手动点击底部输入框，触发评论视图弹窗
    self.viewModel.selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.commentInputView setPlaceholderText:KInputToolBarDefalutDesc];
    [self.commentInputView showCommentInputView];
    return NO;
}

- (void)sendButtonAction {
    // 手动点击底部输入框，触发评论视图弹窗
    self.viewModel.selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.commentInputView setPlaceholderText:KInputToolBarDefalutDesc];
    [self.commentInputView showCommentInputView];
}

#pragma mark - 私有方法
- (void)seg_comementCellAtIndexPath:(NSIndexPath *)indexPath
{
    self.viewModel.selectedIndexPath = indexPath;
    if (indexPath.section == 0) {
        [self.commentInputView setPlaceholderText:KInputToolBarDefalutDesc];
    }else {
        [self.commentInputView setPlaceholderText:[NSString stringWithFormat:@"对%@进行回复：",self.viewModel.activityManager.commentAnswerList[indexPath.row].answNick]];
    }
    [self.commentInputView showCommentInputView];
}

#pragma mark - getter
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - kNavigationBarAndStatusBarHeight - KSEGInputBarViewHeight - LYSafeAreaBottom()) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kColor_bg;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = kColor_L2;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //        _tableView.tableFooterView = [[UIView alloc] init];
        UIView *footerView = [[UIView alloc] init];
        footerView.backgroundColor = UIColor.orangeColor;
        _tableView.tableFooterView = footerView;
        [_tableView registerClass:[SEGActivityDetailCommentCell class] forCellReuseIdentifier:kActivityDetailCommentCellIdentifier];
        
        if (@available(iOS 11, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }
    }
    return _tableView;
}


- (SEGCommentInputView *)commentInputView {
    if (!_commentInputView) {
        _commentInputView = [[SEGCommentInputView alloc] init];
        _commentInputView.currentViewController = self;//用于广告
        _commentInputView.delegate = self;
        _commentInputView.GDTPosId = KGDTPosIdActivityCommentDetailID;
        [_commentInputView setPlaceholderText:KInputToolBarDefalutDesc];
        [self.view addSubview:_commentInputView];
    }
    return _commentInputView;
}



@end
